#include <nice2d/actions/interpolationaction.h>

std::shared_ptr<InterpolationAction> InterpolationAction::create(InterpolatorType type,
                                                                 std::function<void (float)> fn, float duration)
{
    return std::make_shared<InterpolationAction>(type, fn, duration);
}

class InterpolationActionData
{
public:
    std::shared_ptr<Interpolator> interpolator;
    std::function<void(float)> fn;
    float time = 0.0f;
};

InterpolationAction::InterpolationAction(InterpolatorType type, std::function<void (float)> fn,
                                         float duration):
    FiniteTimeAction(duration),
    data(new InterpolationActionData())
{
    data->interpolator = Interpolator::create(type);
    data->fn = fn;
}

InterpolationAction::~InterpolationAction()
{
}

void InterpolationAction::update(float deltaTime)
{
    auto owner = getOwner();
    if (owner.expired())
        return;

    data->time += deltaTime;
    float percent = data->time / getDuration();
    if (percent > 1.0f) {
        stop();
    } else {
        float value = data->interpolator->interpolate(percent);
        data->fn(value);
    }
}
